package com.dhy.dbCore.transaction.core;

import com.dhy.dbCore.transaction.util.DefaultTransactionStatus;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;

/**
 * @author 大忽悠
 * @create 2022/6/6 21:01
 */
@Slf4j
public class JdbcTransactionTemplate {
    private DataSourceTransactionManager tm;

    public JdbcTransactionTemplate(DataSourceTransactionManager tm) {
        this.tm = tm;
    }

    public JdbcTransactionTemplate(DataSource dataSource) {
        this.tm = new DataSourceTransactionManager(dataSource);
    }

    public <T> T execute(TransactionCallback<T> action) throws Throwable {
        T result = null;
        DefaultTransactionStatus status = null;
        try {
            status = tm.getTransaction();
            result = action.doInTransaction(status);
        } catch (Throwable ex) {
            tm.rollback(status,ex);
            log.error("事务出错,进行回滚: ",ex);
            return null;
        }
        if (status != null) {
            tm.commit(status);
        }else {
            tm.rollback(new DefaultTransactionStatus(false,false,false),null);
            return null;
        }
        log.info("事务正常提交 ");
        return result;
    }
}
